package com.ad.pet.common.structure.ui.activity;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.webkit.CookieSyncManager;

import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.ad.pet.App;
import com.ad.pet.Logger;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.common.data.AppStatusManager;
import com.ad.pet.common.data.injector.component.ApplicationComponent;
import com.ad.pet.common.data.injector.module.ActivityModule;
import com.ad.pet.common.data.utils.SpUtil;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.constant.AppStatusConstant;
import com.ad.pet.constant.Constant;
import com.ad.pet.utils.LyxUtils;
import com.ad.pet.common.structure.key.TokenKey;
import com.just.agentweb.AgentWebConfig;

import com.umeng.analytics.MobclickAgent;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Cookie;
import okhttp3.HttpUrl;


/**
 * Created by ems on 2017/2/27.
 * activity基类
 */

public abstract class BaseActivity extends AppCompatActivity {
    private static final String TAG = "BaseActivity";
    protected BaseActivity mActivity;
    protected BasePresenter mBasePresenter;
    protected Unbinder mBind;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Logger.v(TAG, " onCreate");

        LyxUtils.changeAppLanguage(this, SpUtil.getInstance().getString(Constant.LANGUAGE,"cn"));
        setContentViewBefore();
        setContentView(layoutResId());
        if (isStatusBarTransparent()) {
            setStatusBarTransparent();
        }
        mActivity = this;
        initStatus();
        mBind = ButterKnife.bind(this);
        initInject();
        initViews();
        initData();
        initEvents();
        mBasePresenter = getPresenter();
        Logger.e("AppStatusConstant:" + AppStatusManager.getInstance().getAppStatus());
        if (AppStatusManager.getInstance().getAppStatus() == AppStatusConstant.STATUS_FORCE_KILLED) {
            Navigation.restartApp(mActivity);
            finish();
        }


    }

    protected void setContentViewBefore() {

    }


    /**
     * 设置透明状态栏
     */
    private void setStatusBarTransparent() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            Window window = getWindow();
//            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT);
//        }

    }

    protected boolean isStatusBarTransparent() {
        return false;
    }

    protected abstract void initViews();


    protected abstract void initData();


    protected abstract void initEvents();


    public ActivityModule getActivityModule() {
        return new ActivityModule(this);

    }

    public ApplicationComponent getApplicationComponent() {
        return App.getApp().getApplicationComponent();
    }

    protected void initStatus() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onDestroy() {
        if (mBasePresenter != null) {
            mBasePresenter.onDestroy();
            mBasePresenter = null;
        }
        if (mBind != null) {
            mBind.unbind();
            mBind = null;
        }
        super.onDestroy();
    }

    //内存变化时调用
    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        Logger.d("onTrimMemory..." + level);
    }

    public abstract void initInject();

    protected abstract int layoutResId();

    protected abstract BasePresenter getPresenter();

    public boolean hasLogin() {
        return !TextUtils.isEmpty(getAccessToken());
    }

    protected String getAccessToken() {
        return SpUtil.getInstance().getString(TokenKey.TOKEN, "");
    }

    /**
     * 将cookie同步到WebView
     */
    protected void syncCookie() {

//        AgentWebConfig.removeAllCookies();
//        AgentWebConfig.syncCookie(getString(R.string.ip_host),"");
//        AgentWebConfig.syncCookie(getString(R.string.ip_default),"");
        List<Cookie> cookies = (((PersistentCookieJar) App.getApp().getApplicationComponent().getOkHttpClient().cookieJar())).loadForRequest(HttpUrl.parse(getString(R.string.top_host)));


        StringBuffer sb = new StringBuffer();


        for (Cookie cookie : cookies) {

            String cookieName = cookie.name();
            String cookieValue = cookie.value();
            if (!TextUtils.isEmpty(cookieName)
                    && !TextUtils.isEmpty(cookieValue) && TextUtils.equals(cookieName, "PHPSESSID")) {
                sb.append(cookieName + "=");
                sb.append(cookieValue + ";");
            }
        }
        sb.append("platform" + "=");
        sb.append("android" + ";");
        CookieSyncManager.createInstance(mActivity);
        Logger.e("cookie:" + sb.toString());
        AgentWebConfig.syncCookie(getString(R.string.top_host_point), sb.toString());
    }


    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

    }


}
